#include "stb_image.h"
#include "opengl/opengl_texture.h"

namespace engine
{
    ColorTexture2D::ColorTexture2D(const char *path)
    {
        int w, h, channels;
        stbi_set_flip_vertically_on_load(true);
        void *pixels = stbi_load(path, &w, &h, &channels, 0);
        ENGINE_ASSERT(pixels, "file can't load: " + path);
        if (channels == 1)
        {
            internal_format_ = GL_RED;
            data_format_ = GL_RED;
        }
        else if (channels == 3)
        {
            internal_format_ = GL_RGB8;
            data_format_ = GL_RGB;
        }
        else if (channels == 4)
        {
            internal_format_ = GL_RGBA8;
            data_format_ = GL_RGBA;
        }
        ENGINE_ASSERT(internal_format_ && data_format_, "Invalid internal_format or data_format");

        this->width = w;
        this->height = h;

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        glTexImage2D(GL_TEXTURE_2D, 0, internal_format_, w, h, 0, data_format_, GL_UNSIGNED_BYTE, (const void *)pixels);
        glGenerateMipmap(GL_TEXTURE_2D);

        stbi_image_free(pixels);
        ENGINE_DEBUG("load texture - file: {} ,id: {}.\n", path, texture);
    }
    ColorTexture2D::~ColorTexture2D()
    {
    }
}